package com.yixun.qfbao.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yixun.qfbao.api.service.PremisesRecommenderService;
import com.yixun.qfbao.api.service.V10BindService;
import com.yixun.qfbao.apidto.*;
import com.yixun.qfbao.apidto.v10dto.*;
import com.yixun.qfbao.config.V10ApiConfig;
import com.yixun.qfbao.config.V10InterfaceAddr;
import com.yixun.qfbao.constant.StringConstant;
import com.yixun.qfbao.dao.ApiLogDao;
import com.yixun.qfbao.dao.OtherCompanyDao;
import com.yixun.qfbao.mapper.CompanyMapper;
import com.yixun.qfbao.mapper.PremisesImageMapper;
import com.yixun.qfbao.mapper.ReportExternalMapper;
import com.yixun.qfbao.model.*;
import com.yixun.qfbao.model.dto.*;
import com.yixun.qfbao.model.enums.*;
import com.yixun.qfbao.service.*;
import com.yixun.qfbao.util.DateStyle;
import com.yixun.qfbao.util.DateUtils;
import com.yixun.qfbao.util.HttpApi;
import com.yixun.qfbao.util.ParseUtils;
import com.yixun.qfbao.xf.mapper.ApartmentLayoutDiagramMapper;
import com.yixun.qfbao.xf.mapper.CustomerPremisesMapper;
import com.yixun.qfbao.xf.model.ApartmentLayoutDiagram;
import com.yixun.qfbao.xf.model.CustomerPremises;
import com.yixun.qfbao.xf.model.Premises;
import com.yixun.qfbao.xf.model.dto.ApartmentLayoutDiagramDto;
import com.yixun.qfbao.xf.model.dto.PremisesDynamicDto;
import com.yixun.qfbao.xf.model.enums.*;
import com.yixun.qfbao.xf.service.CustomerPremisesService;
import com.yixun.qfbao.xf.service.PremisesService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class V10BindServiceImpl implements V10BindService {
    private static final Logger logger = LoggerFactory.getLogger(V10BindServiceImpl.class);
    @Autowired
    ApiLogDao apiLogDao;
    @Autowired
    CompanyMapper companyMapper;
    @Autowired
    PremisesImageMapper imageMapper;
    @Autowired
    ApartmentLayoutDiagramMapper apartmentLayoutDiagramMapper;
    @Autowired
    V10ApiConfig v10ApiConfig;
    @Autowired
    AreaService areaService;
    @Autowired
    BaseCodeValueService baseCodeValueService;
    @Autowired
    PremisesService premisesService;
    @Autowired
    PremisesRelationExternalService premisesRelationExternalService;
    @Autowired
    OtherCompanyDao otherCompanyDao;
    @Autowired
    PremisesDynamicExternalService premisesDynamicExternalService;
    @Autowired
    ReportExternalService reportExternalService;
    @Autowired
    OtherSysUserService otherSysUserService;
    @Autowired
    PartnerInfoService partnerInfoService;

    @Autowired
    CustomerPremisesService customerPremisesService;

    @Autowired
    ReportExternalMapper reportExternalMapper;

    @Autowired
    CustomerPremisesMapper customerPremisesMapper;
    @Autowired
    PremisesRecommenderService premisesRecommenderService;

    @Autowired
    private ReportModelService reportModelService;

    @Autowired
    private PremisesRelationService premisesRelationService;

    /**
     * 楼盘同步接口
     * 接口描述：渠道王添加新房并审核通过后，可调用此接口将新房楼盘的信息添加到v10系统新房楼盘数据表中
     * URL:/v1/fyapi/saveFirsthandEstate
     *
     * @param dto
     * @param otherCompanyList
     * @return
     */
    @Override
    @Async
    public List<BaseResponseDto> saveFirsthandEstate(Premises dto, List<OtherCompany> otherCompanyList) {
        logger.info("push V10 saveFirsthandEstate info : {}",JSONObject.toJSONString(otherCompanyList));
        List<BaseResponseDto> list = new ArrayList<>();
        try {
            //整理参数
            SaveFirsthandEstateReqDto reqDto = setSaveFirstHandEstateDto(dto);
            //楼盘报备模板信息
            reqDto.setReportModels(buildReportModels(dto));
            for (OtherCompany oc : otherCompanyList) {
                reqDto.setCompanyUuid(oc.getCompanyUuid());
                reqDto.setAppId(oc.getAppid());
                reqDto.setAppkey(oc.getAppkey());
                //查询楼盘关联表中是否有关联数据
                PremisesRelationExternalDto premisesRelationExternalDto = new PremisesRelationExternalDto();
                premisesRelationExternalDto.setIsDeleted(DelFlagEnum.UNDEL.getNo());
                premisesRelationExternalDto.setSysId(ExternalSysEnum.V10.getCode());
                premisesRelationExternalDto.setExternalCompanyId(oc.getCompanyUuid());
                premisesRelationExternalDto.setPremisesId(dto.getId());
                List<PremisesRelationExternal> premisesRelationExternalList = premisesRelationExternalService.selectListByDto(premisesRelationExternalDto);
                if (premisesRelationExternalList != null && premisesRelationExternalList.size() > 0) {
                    reqDto.setEstateUuid(premisesRelationExternalList.get(0).getExternalId());
                    /** 查询楼盘外部关系  */
                    PremisesRelationDto relationDto = new PremisesRelationDto();
                    relationDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
                    relationDto.setPremisesId(premisesRelationExternalList.get(0).getPremisesId());
                    relationDto.setStatus(RelationStatusEnum.VALID.getNo());
                    List<PremisesRelation> premisesRelationList = premisesRelationService.selectListByDto(relationDto);
                    /** 判断指定分销商是否绑定v10 */
                    boolean flag = true;
                    for (PremisesRelation premisesRelation : premisesRelationList){
                        if ((premisesRelation.getAgentCompanyId().equals(oc.getChannelCompanyId()))){
                            flag = false;
                            break;
                        }
                    }
                    /** 如果存在指定的分销绑定了v10 就继续执行一下操作 否则跳出本次循环 */
                    if (flag){
                        continue;
                    }
                } else {
                    reqDto.setEstateUuid(null);
                }
                ApiLogDto apiLog = new ApiLogDto();
                apiLog.setOtherRelationId(Long.toString(dto.getId()));
                apiLog.setCompanyId(dto.getCompanyId());
                apiLog.setOtherCompanyId(oc.getCompanyUuid());
                apiLog.setBusinessType(ApiActionEnum.PREMISES_AYS.getNo());
                apiLog.setPremisesId(dto.getId());
                apiLog.setPremisesName(dto.getName());
                apiLog.setBusinessTime(new Date());
                //请求接口
                String result = HttpApi.doPostV10(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.saveFirsthandEstate, JSONObject.toJSONString(reqDto), oc.getAppid(), oc.getAppkey(), oc.getCompanyUuid(), apiLog);
//            String result = "";
                BaseResponseDto<String> brDto = JSONObject.parseObject(result, BaseResponseDto.class);
                //返回成功将其更新到 关联关系中
                if (V10ApiResponseCodeEnum.SUCCESS.getNo().equals(brDto.getResponseCode())
                        && (premisesRelationExternalList == null || premisesRelationExternalList.size() == 0)) {
                    PremisesRelationExternalDto pre = new PremisesRelationExternalDto();
                    pre.setAgentCompanyId(oc.getChannelCompanyId());
                    pre.setExternalCompanyId(oc.getCompanyUuid());
                    pre.setPremisesId(dto.getId());
                    pre.setExternalId(brDto.getData());
                    pre.setSysId(ExternalSysEnum.V10.getCode());
                    premisesRelationExternalService.create(pre);
                }
                list.add(brDto);
            }
        } catch (Exception e) {
            logger.error("楼盘同步调用失败:{}", e);
            apiLogDao.addApiLog(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.saveFirsthandEstate, e.getMessage(), "楼盘同步异常");
        }
        return list;
    }

    private List<PremisesReportModelDto> buildReportModels(Premises dto) {
        ReportModelDto reportModelDto = new ReportModelDto();
        reportModelDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        reportModelDto.setPremisesId(dto.getId());
        reportModelDto.setModelType(ModelTypeEnum.customer_config.getCode());//2为自定义
        reportModelDto.setOrders(" t.model_order ");
        List<ReportModel> list = reportModelService.selectListByDto(reportModelDto);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        List<PremisesReportModelDto> reportModels = new ArrayList<>();
        for (ReportModel rm : list) {
            PremisesReportModelDto prm = new PremisesReportModelDto();
            prm.setModelColumn(rm.getModelColumn());
            prm.setModelId(rm.getId());
            reportModels.add(prm);
        }
        return reportModels;
    }

    /**
     * 接口描述：保存新房楼盘动态
     * URL:/v1/fyapi/saveFirsthandEstateDynamic
     *
     * @param list
     * @param premisesDynamic
     * @return
     */
    @Override
    @Async
    public List<BaseResponseDto> saveFirsthandEstateDynamic(List<PremisesDynamicExternal> list, PremisesDynamicDto premisesDynamic) {
        List<BaseResponseDto> returnList = new ArrayList<>();
        //记录日志
        ApiLogDto apiLog = new ApiLogDto();
        apiLog.setCompanyId(premisesDynamic.getCompanyId());
        apiLog.setBusinessType(ApiActionEnum.PREMISES_AYS.getNo());
        apiLog.setPremisesId(premisesDynamic.getPremisesId());
        apiLog.setPremisesName(premisesDynamic.getPremisesName());
        apiLog.setBusinessTime(premisesDynamic.getCreateTime());
        try {
            for (PremisesDynamicExternal pde : list) {
                if (premisesDynamic.getId() == null || pde.getDynamicId().equals(premisesDynamic.getId())) {
                    SaveFirsthandEstateDynamicReqDto reqDto = new SaveFirsthandEstateDynamicReqDto();
                    //楼盘uuid
                    reqDto.setEstateUuid(pde.getPremisesUuid());
                    //内容
                    reqDto.setContent(premisesDynamic.getContent());
                    //楼盘动态uuid
                    reqDto.setDynamicUuid(pde.getDynamicUuid());
                    //发布模式:1,2(新闻公告、内部邮箱)
                    reqDto.setIssueMode("1");
                    // 显示状态 0 不显示 ，1 显示
                    reqDto.setShowStatus(Boolean.TRUE.equals(premisesDynamic.getCanSee()) ? "1" : "0");
                    //备注
//        reqDto.setRemark(dto.getRemark());
                    //渠道动态id
                    if (premisesDynamic.getId() != null) {
                        reqDto.setChannelDynamicId(premisesDynamic.getId().toString());
                    }
                    reqDto.setTitle(premisesDynamic.getTitle());
                    //1.获取公司信息
                    OtherCompanyDto ocDto = new OtherCompanyDto();
                    ocDto.setIsDeleted(DelFlagEnum.UNDEL.getNo());
                    ocDto.setCompanyUuid(pde.getExternalCompanyId());
                    OtherCompany otherCompany = otherCompanyDao.selectByDto(ocDto);
                    //2.调用api
                    String result = HttpApi.doPostV10(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.saveFirsthandEstateDynamic, JSONObject.toJSONString(reqDto), otherCompany.getAppid(), otherCompany.getAppkey(), otherCompany.getCompanyUuid(), apiLog);
                    BaseResponseDto<String> brDto = JSONObject.parseObject(result, BaseResponseDto.class);
                    returnList.add(brDto);
                    if (V10ApiResponseCodeEnum.SUCCESS.getNo().equals(brDto.getResponseCode())) {
                        PremisesDynamicExternalDto premisesDynamicExternalDto = new PremisesDynamicExternalDto();
                        BeanUtils.copyProperties(pde, premisesDynamicExternalDto);
                        premisesDynamicExternalDto.setDynamicUuid(brDto.getData());
                        premisesDynamicExternalDto.setSysId(ExternalSysEnum.V10.getCode());
                        premisesDynamicExternalDto.setIsDeleted(DelFlagEnum.UNDEL.getNo());
                        premisesDynamicExternalService.saveOrUpdate(premisesDynamicExternalDto);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("楼盘动态异常: {}", e);
            apiLog.setUrl(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.saveFirsthandEstateDynamic);
            apiLog.setResponseContent(e.getMessage());

            apiLogDao.create(apiLog);
//          apiLogDao.addApiLog(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.saveFirsthandEstateDynamic,e.getMessage(),"楼盘动态同步异常");
        }

        return returnList;

    }

    /**
     * 接口描述：渠道王对其推送到V10系统的楼盘进行上下架操作。
     * URL:/v1/fyapi/issueFirsthandEstate
     *
     * @param list
     * @param status
     * @return
     */
    @Override
    @Async
    public List<BaseResponseDto> issueFirsthandEstate(Premises premises, List<PremisesRelationExternal> list, String status) {

        List<BaseResponseDto> returnList = new ArrayList<>();
        List<IssueFirsthandEstateReqDto> issueFirsthandEstateReqDtoList = new ArrayList<IssueFirsthandEstateReqDto>();
        ApiLogDto apiLogDto = new ApiLogDto();
        apiLogDto.setPremisesId(premises.getId());
        apiLogDto.setPremisesName(premises.getName());
        apiLogDto.setCompanyId(premises.getCompanyId());
        apiLogDto.setPremisesId(premises.getId());
        apiLogDto.setPremisesName(premises.getName());
        apiLogDto.setOtherRelationId(Long.toString(premises.getId()));
        apiLogDto.setUrl(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.issueFirsthandEstate);
        if ("0".equals(status) || "2".equals(status)) {
            apiLogDto.setBusinessType(ApiActionEnum.PREMISES_AYS_TAKEAWAY.getNo());
        } else if ("1".equals(status)) {
            apiLogDto.setBusinessType(ApiActionEnum.PREMISES_AYS_PUTAWAY.getNo());
        }

        for (PremisesRelationExternal pre : list) {
            try {
                IssueFirsthandEstateReqDto issueFirsthandEstateReqDto = new IssueFirsthandEstateReqDto();
                issueFirsthandEstateReqDto.setEstateUuid(pre.getExternalId());
                issueFirsthandEstateReqDto.setChannelPremises(pre.getPremisesId().toString());
                if (PremisesStatusEnum.type1.getNo().equals(status)) {
                    issueFirsthandEstateReqDto.setChannelIssuedStatus(status);
                } else {
                    issueFirsthandEstateReqDto.setChannelIssuedStatus(PremisesStatusEnum.type0.getNo());
                }
                issueFirsthandEstateReqDto.setCompanyUuid(pre.getExternalCompanyId());
                //获取公司状态
                OtherCompanyDto ocDto = new OtherCompanyDto();
                ocDto.setIsDeleted(DelFlagEnum.UNDEL.getNo());
                ocDto.setCompanyUuid(pre.getExternalCompanyId());
                ocDto.setChannelCompanyId(pre.getAgentCompanyId());
                //日志公司信息
                apiLogDto.setOtherCompanyId(pre.getExternalCompanyId());


                OtherCompany otherCompany = otherCompanyDao.selectByDto(ocDto);
                if (null == otherCompany) {
                    apiLogDto.setRemark("无匹配关系，楼盘上下架异常");
                    apiLogDao.create(apiLogDto);
                    // apiLogDao.addApiLog(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.issueFirsthandEstate, "无匹配关系","楼盘上下架异常");
                    continue;
                }
                issueFirsthandEstateReqDto.setAppkey(otherCompany.getAppkey());
                issueFirsthandEstateReqDto.setAppId(otherCompany.getAppid());

                apiLogDto.setOtherCompanyId(pre.getExternalCompanyId());
                String result = HttpApi.doPostV10(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.issueFirsthandEstate, JSONObject.toJSONString(issueFirsthandEstateReqDto), issueFirsthandEstateReqDto.getAppId(), issueFirsthandEstateReqDto.getAppkey(), issueFirsthandEstateReqDto.getCompanyUuid(), apiLogDto);
                BaseResponseDto baseResponseDto = JSONObject.parseObject(result, BaseResponseDto.class);
                returnList.add(baseResponseDto);

            } catch (Exception ex) {
                logger.error("楼盘上下架异常：{}", ex);
                apiLogDto.setResponseContent(ex.getMessage());
                apiLogDto.setRemark("楼盘上下架异常");
                apiLogDao.create(apiLogDto);
                // apiLogDao.addApiLog(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.issueFirsthandEstate,ex.getMessage(),"楼盘上下架异常");
            }

        }

        return returnList;
    }

    /**
     * 接口描述：渠道王对V10系统报备到其系统中的新房楼盘的审核状态进行更新操作。
     * URL:/v1/fyapi/updateFirstHandIntentionAuditStatus
     *
     * @param reqDto
     * @return
     */
    @Override
    @Async
    public BaseResponseDto updateFirsthandIntentionAuditStatus(UpdateFirsthandIntentionAuditStatusReqDto reqDto, SyncFollowAndAffixReqDto syncReqDto) {

        BaseResponseDto brDto = new BaseResponseDto();
        ApiLogDto apiLogDto = new ApiLogDto();

        if (reqDto.getIntentionUuid() == null) {
            brDto.setResponseMessage("报备uuid不能为空");
            return brDto;
        }
        if (reqDto.getAuditStatus() == null) {
            brDto.setResponseMessage("审核状态不能为空");
        }
        try {
            //状态转换
            if((CustomerStatusEnum.not_visited.getNo().equals(reqDto.getOldAuditStatus()) || CustomerStatusEnum.normal.getNo().equals(reqDto.getOldAuditStatus())) &&
                    CustomerStatusEnum.no_valid.getNo().equals(reqDto.getAuditStatus())){
                // 如果当前报备状态为未到访，超时推送给V10的状态为报备无效：8
                reqDto.setAuditStatus("8");
            }else{
                reqDto.setAuditStatus(switchStatus(reqDto.getAuditStatus()));
            }
            logger.info("updateFirsthandIntentionAuditStatus cpOLdStatus:{}, dtoAuditStatus:{}, cpid:{}", reqDto.getOldAuditStatus(), reqDto.getAuditStatus(),
                    reqDto.getIntentionUuid());
            reqDto.setOldAuditStatus(switchStatus(reqDto.getOldAuditStatus()));
            //获取报备绑定关系
            ReportExternalDto reportExternalDto = new ReportExternalDto();
            reportExternalDto.setReportUuid(reqDto.getIntentionUuid());
            reportExternalDto.setIsDeleted(DelFlagEnum.UNDEL.getNo());
            List<ReportExternal> list = reportExternalService.selectListByDto(reportExternalDto);

            if (list == null || list.size() == 0) {
                throw new RuntimeException("未获取报备信息");
            }

            //根据报备获取绑定楼盘
            PremisesRelationExternalDto preDto = new PremisesRelationExternalDto();
            preDto.setExternalId(list.get(0).getPremisesUuid());
            preDto.setIsDeleted(DelFlagEnum.UNDEL.getNo());
            List<PremisesRelationExternal> premisesRelationList = premisesRelationExternalService.selectListByDto(preDto);
            if (premisesRelationList == null || premisesRelationList.size() == 0) {
                throw new RuntimeException("报备相关楼盘信息为空");
            }
            //根据楼盘获取绑定公司
            OtherCompanyDto otherCompany = new OtherCompanyDto();
            otherCompany.setIsDeleted(DelFlagEnum.UNDEL.getNo());
            otherCompany.setCompanyUuid(premisesRelationList.get(0).getExternalCompanyId());
            List<OtherCompany> otherCompanyList = otherCompanyDao.selectListByDto(otherCompany);
            if (otherCompanyList == null || otherCompanyList.size() == 0) {
                // throw new RuntimeException("公司相关信息为空,未发送请求");
                apiLogDto.setRequestContent(JSONObject.toJSONString(reqDto));
                //日志类型
                if (CustomerStatusEnum.no_valid.getNo().equals(reqDto.getAuditStatus())) {
                    apiLogDto.setBusinessType(ApiActionEnum.REPORT_AUDIT_NO.getNo());
                } else if (CustomerStatusEnum.not_visited.getNo().equals(reqDto.getAuditStatus())) {
                    apiLogDto.setBusinessType(ApiActionEnum.REPORT_AUDIT_YES.getNo());
                } else if (CustomerStatusEnum.has_visited.getNo().equals(reqDto.getAuditStatus())) {
                    apiLogDto.setBusinessType(ApiActionEnum.REPORT_AUDIT_VISITED.getNo());
                }
                apiLogDto.setContent("公司相关信息为空,未发送请求");
                apiLogDao.addApiLog(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.updateFirsthandIntentionAuditStatus, "公司相关信息为空,未发送请求", "报备审核同步异常");
                return brDto;
            }
            //日志参数
            apiLogDto.setOtherCompanyId(otherCompanyList.get(0).getCompanyUuid());
            Premises premises = premisesService.getSimpleById(premisesRelationList.get(0).getPremisesId());
            if (null != premises) {
                apiLogDto.setCompanyId(premises.getCompanyId());
                apiLogDto.setPremisesId(premises.getId());
                apiLogDto.setPremisesName(premises.getName());
            }
            //报备及人员信息
            CustomerPremises customerPremises = customerPremisesService.selectById(list.get(0).getReportId());
            PartnerInfo partnerInfo = partnerInfoService.selectById(customerPremises.getStaffId());
            apiLogDto.setOtherRelationId(Long.toString(list.get(0).getReportId()));
            if (null != partnerInfo) {
                apiLogDto.setPartnerId(partnerInfo.getId());
                apiLogDto.setPartnerName(partnerInfo.getAccountName());
            }
            //日志类型
            if (CustomerStatusEnum.no_valid.getNo().equals(reqDto.getAuditStatus())) {
                apiLogDto.setBusinessType(ApiActionEnum.REPORT_AUDIT_NO.getNo());
            } else if (CustomerStatusEnum.not_visited.getNo().equals(reqDto.getAuditStatus())) {
                apiLogDto.setBusinessType(ApiActionEnum.REPORT_AUDIT_YES.getNo());
            } else if (CustomerStatusEnum.has_visited.getNo().equals(reqDto.getAuditStatus())) {
                apiLogDto.setBusinessType(ApiActionEnum.REPORT_AUDIT_VISITED.getNo());
            }
            String result = HttpApi.doPostV10(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.updateFirsthandIntentionAuditStatus, JSONObject.toJSONString(reqDto), otherCompanyList.get(0).getAppid(), otherCompanyList.get(0).getAppkey(), otherCompanyList.get(0).getCompanyUuid(), apiLogDto);

            logger.info("巧渠道调用updateFirsthandIntentionAuditStatus后的返回结果" + result);

            brDto = JSONObject.parseObject(result, BaseResponseDto.class);

            if (!"1".equals(brDto.getResponseCode())) {
                //调用失败
                brDto.setResponseCode(ResultEnum.FAIL.getNo());

                brDto.setResponseMessage("同步审核状态失败！");

                return brDto;
            }


            V10IntentionFollowDto followVo = syncReqDto.getFollowVo();

            followVo.setOldAuditStatus(switchStatus(followVo.getOldAuditStatus()));

            followVo.setNewAuditStatus(switchStatus(followVo.getNewAuditStatus()));

            syncReqDto.setFollowVo(followVo);
            apiLogDto.setBusinessType(ApiActionEnum.FOLLOW_AYS.getNo());
            result = HttpApi.doPostV10(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.syncFollowAndAffix, JSONObject.toJSONString(syncReqDto), otherCompanyList.get(0).getAppid(), otherCompanyList.get(0).getAppkey(), otherCompanyList.get(0).getCompanyUuid(), apiLogDto);

            logger.info("巧渠道调用syncFollowAndAffix后的返回结果" + result);

            brDto = JSONObject.parseObject(result, BaseResponseDto.class);

            if (Objects.isNull(brDto) || StringUtils.isBlank(brDto.getResponseCode()) || !"1".equals(brDto.getResponseCode())) {
                //调用失败
                brDto.setResponseCode(ResultEnum.FAIL.getNo());

                brDto.setResponseMessage("同步跟进和附件失败！");

                return brDto;
            }


        } catch (Exception e) {
            logger.error("updateFirsthandIntentionAuditStatus error：{}", e);
            apiLogDto.setRequestContent(JSONObject.toJSONString(reqDto));
            //日志类型
            if (CustomerStatusEnum.no_valid.getNo().equals(reqDto.getAuditStatus())) {
                apiLogDto.setBusinessType(ApiActionEnum.REPORT_AUDIT_NO.getNo());
            } else if (CustomerStatusEnum.not_visited.getNo().equals(reqDto.getAuditStatus())) {
                apiLogDto.setBusinessType(ApiActionEnum.REPORT_AUDIT_YES.getNo());
            } else if (CustomerStatusEnum.has_visited.getNo().equals(reqDto.getAuditStatus())) {
                apiLogDto.setBusinessType(ApiActionEnum.REPORT_AUDIT_VISITED.getNo());
            }
            apiLogDto.setContent(e.getMessage());
            apiLogDao.addApiLog(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.updateFirsthandIntentionAuditStatus, e.getMessage(), "报备审核同步异常");
        }
        return brDto;
    }

    /**
     * 接口描述：渠道王对V10系统报备到其系统中的新房楼盘的交易状态进行更新操作。
     * URL:/v1/fyapi/updateFirstHandIntentionTradeStatus
     *
     * @param reqDto
     * @return
     */
    @Override
//    @Async
    public BaseResponseDto updateFirsthandIntentionTradeStatus(UpdateFirsthandIntentionTradeStatusReqDto reqDto, SyncFollowAndAffixReqDto syncReqDto) {
        BaseResponseDto brDto = new BaseResponseDto();
        ApiLogDto apiLogDto = new ApiLogDto();
        if (reqDto.getIntentionUuid() == null) {
            brDto.setResponseMessage("报备uuid不能为空");
            return brDto;
        }
        if (reqDto.getTradeStatus() == null) {
            brDto.setResponseMessage("交易状态不能为空");
        }
        try {
            //获取报备绑定关系
            ReportExternalDto reportExternalDto = new ReportExternalDto();
            reportExternalDto.setReportUuid(reqDto.getIntentionUuid());
            reportExternalDto.setIsDeleted(DelFlagEnum.UNDEL.getNo());
            List<ReportExternal> list = reportExternalService.selectListByDto(reportExternalDto);

            if (list == null || list.size() == 0) {
                throw new RuntimeException("未获取报备信息");
            }

            //根据报备获取绑定楼盘
            PremisesRelationExternalDto preDto = new PremisesRelationExternalDto();
            preDto.setExternalId(list.get(0).getPremisesUuid());
            preDto.setIsDeleted(DelFlagEnum.UNDEL.getNo());
            List<PremisesRelationExternal> premisesRelationList = premisesRelationExternalService.selectListByDto(preDto);
            if (premisesRelationList == null || premisesRelationList.size() == 0) {
                throw new RuntimeException("报备相关楼盘信息为空");
            }
            //根据楼盘获取绑定公司
            OtherCompanyDto otherCompany = new OtherCompanyDto();
            otherCompany.setIsDeleted(DelFlagEnum.UNDEL.getNo());
            otherCompany.setCompanyUuid(premisesRelationList.get(0).getExternalCompanyId());
            List<OtherCompany> otherCompanyList = otherCompanyDao.selectListByDto(otherCompany);
            if (otherCompanyList == null || otherCompanyList.size() == 0) {
                // throw new RuntimeException("公司相关信息为空,未发送请求");
                apiLogDto.setRequestContent(JSONObject.toJSONString(reqDto));
                //日志类型
                if (ConfirmStatusEnum.payDeposit.getNo().equals(reqDto.getTradeStatus())) {
                    apiLogDto.setBusinessType(ApiActionEnum.REPORT_AUDIT_PAYDEPOSIT.getNo());
                } else if (ConfirmStatusEnum.subscribe.getNo().equals(reqDto.getTradeStatus())) {
                    apiLogDto.setBusinessType(ApiActionEnum.REPORT_AUDIT_SUBSCRIBE.getNo());
                } else if (ConfirmStatusEnum.sign.getNo().equals(reqDto.getTradeStatus())) {
                    apiLogDto.setBusinessType(ApiActionEnum.REPORT_AUDIT_SIGN.getNo());
                } else if (ConfirmStatusEnum.sign_fail.getNo().equals(reqDto.getTradeStatus())) {
                    apiLogDto.setBusinessType(ApiActionEnum.REPORT_DEAL_NO.getNo());
                }
                apiLogDto.setContent("公司相关信息为空,未发送请求");
                apiLogDao.create(apiLogDto);
                return brDto;
            }
            //日志参数
            apiLogDto.setOtherCompanyId(otherCompanyList.get(0).getCompanyUuid());
            Premises premises = premisesService.getSimpleById(premisesRelationList.get(0).getPremisesId());
            if (null != premises) {
                apiLogDto.setCompanyId(premises.getCompanyId());
                apiLogDto.setPremisesId(premises.getId());
                apiLogDto.setPremisesName(premises.getName());
            }
            //报备及人员信息
            CustomerPremises customerPremises = customerPremisesService.selectById(list.get(0).getReportId());
            PartnerInfo partnerInfo = partnerInfoService.selectById(customerPremises.getStaffId());
            apiLogDto.setOtherRelationId(Long.toString(list.get(0).getReportId()));
            if (null != partnerInfo) {
                apiLogDto.setPartnerId(partnerInfo.getId());
                apiLogDto.setPartnerName(partnerInfo.getAccountName());
            }
            //日志类型
            if (ConfirmStatusEnum.payDeposit.getNo().equals(reqDto.getTradeStatus())) {
                apiLogDto.setBusinessType(ApiActionEnum.REPORT_AUDIT_PAYDEPOSIT.getNo());
            } else if (ConfirmStatusEnum.subscribe.getNo().equals(reqDto.getTradeStatus())) {
                apiLogDto.setBusinessType(ApiActionEnum.REPORT_AUDIT_SUBSCRIBE.getNo());
            } else if (ConfirmStatusEnum.sign.getNo().equals(reqDto.getTradeStatus())) {
                apiLogDto.setBusinessType(ApiActionEnum.REPORT_AUDIT_SIGN.getNo());
            } else if (ConfirmStatusEnum.sign_fail.getNo().equals(reqDto.getTradeStatus())) {
                apiLogDto.setBusinessType(ApiActionEnum.REPORT_DEAL_NO.getNo());
            }

            String result = HttpApi.doPostV10(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.updateFirsthandIntentionTradeStatus, JSONObject.toJSONString(reqDto), otherCompanyList.get(0).getAppid(), otherCompanyList.get(0).getAppkey(), otherCompanyList.get(0).getCompanyUuid(), apiLogDto);


            logger.info("巧渠道调用updateFirsthandIntentionTradeStatus后的返回结果" + result);

            brDto = JSONObject.parseObject(result, BaseResponseDto.class);

            if (!"1".equals(brDto.getResponseCode())) {
                //调用失败
                brDto.setResponseCode(ResultEnum.FAIL.getNo());

                brDto.setResponseMessage("同步交易状态失败！");

                return brDto;
            }

            V10IntentionFollowDto followVo = syncReqDto.getFollowVo();

            followVo.setOldAuditStatus(switchStatus(followVo.getOldAuditStatus()));

            followVo.setNewAuditStatus(switchStatus(followVo.getNewAuditStatus()));

            followVo.setOldTradeStatus(reqDto.getOldTradeStatus());

            followVo.setNewTradeStatus(reqDto.getTradeStatus());

            syncReqDto.setFollowVo(followVo);

            apiLogDto.setBusinessType(ApiActionEnum.FOLLOW_AYS.getNo());
            result = HttpApi.doPostV10(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.syncFollowAndAffix, JSONObject.toJSONString(syncReqDto), otherCompanyList.get(0).getAppid(), otherCompanyList.get(0).getAppkey(), otherCompanyList.get(0).getCompanyUuid(), apiLogDto);

            logger.info("巧渠道调用syncFollowAndAffix后的返回结果" + result);

            brDto = JSONObject.parseObject(result, BaseResponseDto.class);

            if (!"1".equals(brDto.getResponseCode())) {
                //调用失败
                brDto.setResponseCode(ResultEnum.FAIL.getNo());

                brDto.setResponseMessage("同步跟进和附件失败！");

                return brDto;
            }

        } catch (Exception e) {
            logger.error("报备交易状态异常：{}", e);
            apiLogDto.setRequestContent(JSONObject.toJSONString(reqDto));
            //日志类型
            if (ConfirmStatusEnum.payDeposit.getNo().equals(reqDto.getTradeStatus())) {
                apiLogDto.setBusinessType(ApiActionEnum.REPORT_AUDIT_PAYDEPOSIT.getNo());
            } else if (ConfirmStatusEnum.subscribe.getNo().equals(reqDto.getTradeStatus())) {
                apiLogDto.setBusinessType(ApiActionEnum.REPORT_AUDIT_SUBSCRIBE.getNo());
            } else if (ConfirmStatusEnum.sign.getNo().equals(reqDto.getTradeStatus())) {
                apiLogDto.setBusinessType(ApiActionEnum.REPORT_AUDIT_SIGN.getNo());
            } else if (ConfirmStatusEnum.sign_fail.getNo().equals(reqDto.getTradeStatus())) {
                apiLogDto.setBusinessType(ApiActionEnum.REPORT_DEAL_NO.getNo());
            }
            apiLogDto.setContent(e.getMessage());
            apiLogDao.create(apiLogDto);
            // apiLogDao.addApiLog(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.updateFirsthandIntentionTradeStatus,e.getMessage(),"报备交易状态同步异常");
        }
        return brDto;
    }

    /**
     * 接口名：updateFirsthandEstateSaleStatus
     * 接口描述：渠道王对其推送到V10系统的楼盘进行上下架操作。销售状态
     * URL:POST /v1/fyapi/firsthandEstate/updateFirsthandEstateSaleStatu
     *
     * @param list
     * @param status
     * @return
     */
    @Override
    @Async
    public List<BaseResponseDto> updateFirsthandEstateSaleStatus(List<PremisesRelationExternal> list, String status) {
        List<BaseResponseDto> brDtoList = new ArrayList<BaseResponseDto>();
        String issuedStatus = null;
        if (status == null) {
            throw new RuntimeException("销售状态不能为空");
        }
        ApiLogDto apiLogDto = new ApiLogDto();
        if (null != list && list.size() > 0) {
            Premises premises = premisesService.getSimpleById(list.get(0).getPremisesId());
            apiLogDto.setPremisesId(premises.getId());
            apiLogDto.setPremisesName(premises.getName());
            apiLogDto.setCompanyId(premises.getCompanyId());
            apiLogDto.setOtherRelationId(Long.toString(premises.getId()));
        }
        if (SaleStatusEnum.type_0.getNo().equals(status)) {
            apiLogDto.setBusinessType(ApiActionEnum.PREMISE_SALE_BEFORE.getNo());
        } else if (SaleStatusEnum.type_1.getNo().equals(status)) {
            apiLogDto.setBusinessType(ApiActionEnum.PREMISES_SALE_ON.getNo());
        } else if (SaleStatusEnum.type_2.getNo().equals(status)) {
            apiLogDto.setBusinessType(ApiActionEnum.PREMISES_SALE_OFF.getNo());
        }
        // 销售状态不影响楼盘上下架状态 待售或售罄之后楼盘下架
//        if(SaleStatusEnum.type_0.getNo().equals(status) || SaleStatusEnum.type_2.getNo().equals(status)){
//            issuedStatus = "0";
//        }

        try {
            for (PremisesRelationExternal pre : list) {
                UpdateFirsthandEstateSaleStatusReqDto reqDto = new UpdateFirsthandEstateSaleStatusReqDto();
                reqDto.setChannelIssuedStatus(issuedStatus);
                reqDto.setEstateUuid(pre.getExternalId());
                reqDto.setSaleStatus(switchPremisesStatus(status));

                OtherCompanyDto otherCompany = new OtherCompanyDto();
                otherCompany.setCompanyUuid(pre.getExternalCompanyId());
                otherCompany.setChannelCompanyId(pre.getAgentCompanyId());
                otherCompany.setIsDeleted(DelFlagEnum.UNDEL.getNo());
                OtherCompany oc = otherCompanyDao.selectByDto(otherCompany);
                apiLogDto.setOtherCompanyId(oc.getCompanyUuid());


                if (oc != null) {
                    String result = HttpApi.doPostV10(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.updateFirsthandEstateSaleStatus, JSONObject.toJSONString(reqDto), oc.getAppid(), oc.getAppkey(), oc.getCompanyUuid(), apiLogDto);
                    BaseResponseDto brDto = JSONObject.parseObject(result, BaseResponseDto.class);
                    brDtoList.add(brDto);
                }

            }
        } catch (Exception e) {
            logger.error("楼盘销售状态变更异常：{}", e);
            apiLogDao.create(apiLogDto);
            // apiLogDao.addApiLog(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.updateFirsthandEstateSaleStatus,e.getMessage(),"楼盘销售状态变更异常");
        }

        return brDtoList;
    }

    /**
     * @param list
     * @return
     */
    @Async
    @Override
    public List<BaseResponseDto> deleteFirsthandEstate(List<PremisesRelationExternal> list) {
        List<BaseResponseDto> brDtoList = new ArrayList<BaseResponseDto>();
        ApiLogDto apiLogDto = new ApiLogDto();
        Premises premises = premisesService.getSimpleById(list.get(0).getPremisesId());
        apiLogDto.setPremisesId(premises.getId());
        apiLogDto.setPremisesName(premises.getName());
        apiLogDto.setBusinessType(ApiActionEnum.PREMISES_DELETE.getNo());
        apiLogDto.setCompanyId(premises.getCompanyId());
        apiLogDto.setUrl(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.deleteFirsthandEstate);
        //将关联关系删除
        try {
            PremisesRelationExternal premisesRelationExternal = new PremisesRelationExternal();
            premisesRelationExternal.setPremisesId(list.get(0).getPremisesId());
            premisesRelationExternal.setIsDeleted(DelFlagEnum.DEL.getNo());
            int i = premisesRelationExternalService.deleteByPremises(premisesRelationExternal);
            if (i <= 0) {
                apiLogDto.setRemark("未删除楼盘关联关系,楼盘删除异常");
                apiLogDao.create(apiLogDto);
                // apiLogDao.addApiLog(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.deleteFirsthandEstate,"未删除楼盘关联关系","楼盘删除异常");
                return null;
            }
            for (PremisesRelationExternal pre : list) {
                DeleteFirsthandEstateReqDto reqDto = new DeleteFirsthandEstateReqDto();
                reqDto.setEstateUuids(new ArrayList<String>() {{
                    add(pre.getExternalId());
                }});


                OtherCompanyDto otherCompany = new OtherCompanyDto();
                otherCompany.setCompanyUuid(pre.getExternalCompanyId());
                otherCompany.setChannelCompanyId(pre.getAgentCompanyId());
                otherCompany.setIsDeleted(DelFlagEnum.UNDEL.getNo());
                OtherCompany oc = otherCompanyDao.selectByDto(otherCompany);
                apiLogDto.setOtherCompanyId(oc.getCompanyUuid());

                if (oc != null) {
                    String result = HttpApi.doPostV10(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.deleteFirsthandEstate, JSONObject.toJSONString(reqDto), oc.getAppid(), oc.getAppkey(), oc.getCompanyUuid(), apiLogDto);
                    BaseResponseDto brDto = JSONObject.parseObject(result, BaseResponseDto.class);
                    brDtoList.add(brDto);
                }

            }
        } catch (Exception e) {
            logger.error("楼盘删除异常：{}", e);
            apiLogDto.setContent(e.getMessage());
            apiLogDto.setRemark("楼盘删除异常");
            apiLogDao.create(apiLogDto);
            // apiLogDao.addApiLog(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.deleteFirsthandEstate,e.getMessage(),"楼盘删除异常");
        }
        return null;
    }

    @Async
    @Override
    public BaseResponseDto syncFollowAndAffix(SyncFollowAndAffixReqDto syncReqDto, String premisesUuid) {
        BaseResponseDto brDto = new BaseResponseDto();
        ApiLogDto apiLogDto = new ApiLogDto();
        apiLogDto.setBusinessType(ApiActionEnum.FOLLOW_AYS.getNo());
        try {

            //根据报备获取绑定楼盘
            PremisesRelationExternalDto preDto = new PremisesRelationExternalDto();
            preDto.setExternalId(premisesUuid);
            preDto.setIsDeleted(DelFlagEnum.UNDEL.getNo());
            List<PremisesRelationExternal> premisesRelationList = premisesRelationExternalService.selectListByDto(preDto);
            if (premisesRelationList == null || premisesRelationList.size() == 0) {
                //throw new RuntimeException("报备相关楼盘信息为空");
                apiLogDto.setUrl(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.syncFollowAndAffix);
                apiLogDto.setRequestContent(JSONObject.toJSONString(syncReqDto));
                apiLogDao.create(apiLogDto);
                return brDto;
            }
            //根据楼盘获取绑定公司
            OtherCompanyDto otherCompany = new OtherCompanyDto();
            otherCompany.setIsDeleted(DelFlagEnum.UNDEL.getNo());
            otherCompany.setCompanyUuid(premisesRelationList.get(0).getExternalCompanyId());
            List<OtherCompany> otherCompanyList = otherCompanyDao.selectListByDto(otherCompany);
            if (otherCompanyList == null || otherCompanyList.size() == 0) {
                // throw new RuntimeException("公司相关信息为空,未发送请求");
                apiLogDto.setUrl(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.syncFollowAndAffix);
                apiLogDto.setRequestContent(JSONObject.toJSONString(syncReqDto));
                apiLogDao.create(apiLogDto);
                return brDto;
            }
            //公司信息
            Premises premises = premisesService.getSimpleById(premisesRelationList.get(0).getPremisesId());
            if (null != premises) {
                apiLogDto.setPremisesId(premises.getId());
                apiLogDto.setPremisesName(premises.getName());
                apiLogDto.setCompanyId(premises.getCompanyId());
            }

            V10IntentionFollowDto followVo = syncReqDto.getFollowVo();
            followVo.setOldAuditStatus(switchStatus(followVo.getOldAuditStatus()));
            followVo.setNewAuditStatus(switchStatus(followVo.getNewAuditStatus()));
            syncReqDto.setFollowVo(followVo);
            apiLogDto.setOtherRelationId(followVo.getIntentionUuid());
            logger.info("==========================>： " + JSON.toJSONString(syncReqDto));
            String result = HttpApi.doPostV10(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.syncFollowAndAffix, JSONObject.toJSONString(syncReqDto), otherCompanyList.get(0).getAppid(), otherCompanyList.get(0).getAppkey(), otherCompanyList.get(0).getCompanyUuid(), apiLogDto);
            brDto = JSONObject.parseObject(result, BaseResponseDto.class);
        } catch (Exception e) {
            logger.error("同步跟进和附件异常：{}", e);
            apiLogDto.setUrl(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.syncFollowAndAffix);
            apiLogDto.setRequestContent(JSONObject.toJSONString(syncReqDto));
            apiLogDao.create(apiLogDto);
            // apiLogDao.addApiLog(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.syncFollowAndAffix,e.getMessage(),"同步跟进和附件异常");
        }

        return brDto;
    }

    /**
     * 同步渠道报备到v10
     *
     * @param customerPremises
     * @return
     */
    @Async
    public BaseResponseDto syncIntention(CustomerPremises customerPremises) {
        BaseResponseDto brDto = new BaseResponseDto();
        ApiLogDto apiLogDto = new ApiLogDto();
        try {
            //查询是否互通
            //根据楼盘获取绑定公司
            OtherCompanyDto otherCompany = new OtherCompanyDto();
            otherCompany.setIsDeleted(DelFlagEnum.UNDEL.getNo());
            otherCompany.setChannelCompanyId(customerPremises.getStaffCompanyId());
            List<OtherCompany> otherCompanyList = otherCompanyDao.selectListByDto(otherCompany);
            if (otherCompanyList == null || otherCompanyList.size() == 0) {
                apiLogDao.addApiLog(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.syncFollowAndAffix, "公司相关信息为空,未发送请求", "同步报备异常");
                return brDto;
            }
            //查询楼盘对应的经济公司绑定关系
            PremisesRelationExternalDto pred = new PremisesRelationExternalDto();
            pred.setIsDeleted(DelFlagEnum.UNDEL.getNo());
            pred.setPremisesId(customerPremises.getPremisesId());
            pred.setAgentCompanyId(customerPremises.getStaffCompanyId());
            List<PremisesRelationExternal> relationExternals = premisesRelationExternalService.selectListByDto(pred);
            if (relationExternals == null || relationExternals.size() == 0) {
                apiLogDao.addApiLog(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.syncFollowAndAffix, "楼盘未同步，请先同步楼盘", "同步报备异常");
                return brDto;
            }
            Premises premises = premisesService.getSimpleById(customerPremises.getPremisesId());
            if (null != premises) {
                apiLogDto.setPremisesId(premises.getId());
                apiLogDto.setPremisesName(premises.getName());
            }
            //查询报备人员
            OtherSysUserDto otherSysUserDto = new OtherSysUserDto();
            otherSysUserDto.setChannelPartnerId(customerPremises.getStaffId());
            otherSysUserDto.setIsDeleted(DelFlagEnum.UNDEL.getNo());
            otherSysUserDto.setCompanyId(customerPremises.getStaffCompanyId());
            List<OtherSysUser> otherSysUsers = otherSysUserService.selectListByDto(otherSysUserDto);
            if (otherSysUsers == null || otherSysUsers.size() == 0) {
                //未同步人员 查询人员
                PartnerInfo partnerInfo = partnerInfoService.selectById(customerPremises.getStaffId());
                if (partnerInfo != null) {
                    otherSysUserDto.setUserPhone(partnerInfo.getPhone());
                    otherSysUserDto.setUserName(partnerInfo.getAccountName());
                }
            } else {
                otherSysUserDto.setUserName(otherSysUsers.get(0).getUserName());
                otherSysUserDto.setUserPhone(otherSysUsers.get(0).getUserPhone());
                otherSysUserDto.setOtherUserId(otherSysUsers.get(0).getOtherUserId());
            }
            apiLogDto.setPartnerId(customerPremises.getStaffId());
            apiLogDto.setPartnerName(otherSysUserDto.getUserName());

            SyncIntentionReqDto reqDto = setSyncIntention(customerPremises, relationExternals.get(0), otherSysUserDto);

            JSONObject params = new JSONObject();
            params.put("reqDTO", reqDto);

            logger.info("==========================>： " + JSON.toJSONString(reqDto));
            String result = HttpApi.doPostV10(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.syncIntention, JSONObject.toJSONString(params), otherCompanyList.get(0).getAppid(), otherCompanyList.get(0).getAppkey(), otherCompanyList.get(0).getCompanyUuid(), apiLogDto);
            brDto = JSONObject.parseObject(result, BaseResponseDto.class);
            if (V10ApiResponseCodeEnum.SUCCESS.getNo().equals(brDto.getResponseCode())) {
                //添加渠道报备关系
                JSONObject jsonObject = JSONObject.parseObject(brDto.getData().toString());
                addReportRelation(customerPremises, jsonObject.getString("intentionUuid"), relationExternals.get(0).getExternalId());

                //判断是否为免审核
                if (FreeAuditEnum.FREE_REPORT_AUDIT.getNo().equals(premises.getFreeAudit())){
                    String uuid = jsonObject.getString("intentionUuid");
                    String newAuditStatus = CustomerStatusEnum.not_visited.getNo();
                    String oldAuditStatus = customerPremises.getCustomerStatus();

                    UpdateFirsthandIntentionAuditStatusReqDto v10ReqDto = new UpdateFirsthandIntentionAuditStatusReqDto();
                    v10ReqDto.setIntentionUuid(uuid);
                    v10ReqDto.setAuditStatus(newAuditStatus);
                    v10ReqDto.setOldAuditStatus(oldAuditStatus);
                    v10ReqDto.setRemark("【" + CustomerStatusEnum.getDescByNo(oldAuditStatus) + "】");
                    v10ReqDto.setReportPeriodTime(customerPremises.getReportPeriodTime() != null ? DateUtils.DateToString(customerPremises.getReportPeriodTime(), DateStyle.YYYY_MM_DD_HH_MM_SS) : null);

                    SyncFollowAndAffixReqDto syncReqDto = new SyncFollowAndAffixReqDto();
                    V10IntentionFollowDto followVo = new V10IntentionFollowDto();
                    followVo.setIntentionUuid(uuid);
                    followVo.setOperationType(OperationTypeEnum.OPERATIONTYPE_3.getCode());
                    followVo.setRemark("报备免审");
                    followVo.setOldAuditStatus(oldAuditStatus);
                    followVo.setNewAuditStatus(newAuditStatus);
                    syncReqDto.setFollowVo(followVo);

                    logger.info("新增报备免审同步v10，v10ReqDto：{}，syncReqDto：{}",v10ReqDto,syncReqDto);
                    //调用审核状态变更接口
                    updateFirsthandIntentionAuditStatus(v10ReqDto,syncReqDto);
                }
            }
        } catch (Exception e) {
            logger.error("同步报备异常：{}", e);
            apiLogDao.addApiLog(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.syncFollowAndAffix, e.getMessage(), "同步报备异常");
        }

        return brDto;
    }

    /**
     * 渠道王对V10系统报备到其系统中的新房楼盘的状态进行异步通知操作。
     *
     * @param intentionUuid
     * @param code
     * @param companyId
     * @return
     */
    @Override
    @Async
    public BaseResponseDto synsNoticeForReport(String intentionUuid, String code, Long companyId, String msg) {
        BaseResponseDto brDto = new BaseResponseDto();
        brDto.setResponseCode(ResultEnum.FAIL.getNo());
        JSONObject object = new JSONObject();
        OtherCompanyDto otherCompanyDto = new OtherCompanyDto();
        otherCompanyDto.setChannelCompanyId(companyId);
        otherCompanyDto.setIsDeleted(DelFlagEnum.UNDEL.getNo());
        List<OtherCompany> otherCompanyList = otherCompanyDao.selectListByDto(otherCompanyDto);
        if (otherCompanyList == null || otherCompanyList.size() == 0) {
            return brDto;
        }
        object.put("intentionUuid", intentionUuid);
        object.put("statusCode", code);
        object.put("statusMsg", msg == null ? ReceiveIntentionErrorCodeEnum.getByNo(code).getMsg() : msg);
        ApiLogDto apiLogDto = new ApiLogDto();
        apiLogDto.setOtherRelationId(intentionUuid);

        String result = HttpApi.doPostV10(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.notifyFirsthandIntentionStatus, object.toJSONString(), otherCompanyList.get(0).getAppid(), otherCompanyList.get(0).getAppkey(), otherCompanyList.get(0).getCompanyUuid(), apiLogDto);
//        String result = HttpApi.doPostV10("https://b13ea585-4a7e-4e01-8a4a-0ce8b5774f49.mock.pstmn.io" + V10InterfaceAddr.notifyFirsthandIntentionStatus, object.toJSONString(), otherCompanyList.get(0).getAppid(), otherCompanyList.get(0).getAppkey(), otherCompanyList.get(0).getCompanyUuid(),apiLogDto);
        brDto = JSONObject.parseObject(result, BaseResponseDto.class);
        return brDto;

    }

    @Override
    @Async
    public void asyncReportInvalidForJob(CustomerPremises cp, Premises premises) {
        ApiLogDto apiLogDtoReport = new ApiLogDto();
        ApiLogDto apiLogDtoFollow = new ApiLogDto();
        if (null != premises) {
            apiLogDtoReport.setCompanyId(premises.getCompanyId());
            apiLogDtoReport.setPremisesId(premises.getId());
            apiLogDtoReport.setPremisesName(premises.getName());
            apiLogDtoReport.setBusinessType(ApiActionEnum.REPORT_AUDIT_NO.getNo());

            apiLogDtoFollow.setCompanyId(premises.getCompanyId());
            apiLogDtoFollow.setPremisesId(premises.getId());
            apiLogDtoFollow.setPremisesName(premises.getName());
            apiLogDtoFollow.setBusinessType(ApiActionEnum.FOLLOW_AYS.getNo());
        }

        //获取公司
        OtherCompanyDto otherCompany = new OtherCompanyDto();
        otherCompany.setIsDeleted(DelFlagEnum.UNDEL.getNo());
        otherCompany.setChannelCompanyId(cp.getStaffCompanyId());
        if(Objects.isNull(cp.getStaffCompanyId())){
            cp = customerPremisesService.selectById(cp.getId());
            otherCompany.setChannelCompanyId(cp.getStaffCompanyId());
        }
        List<OtherCompany> otherCompanyList = otherCompanyDao.selectListByDto(otherCompany);
        if (otherCompanyList == null || otherCompanyList.size() == 0) {
            return;
        }
        //查询楼盘对应的经济公司绑定关系
        PremisesRelationExternalDto pred = new PremisesRelationExternalDto();
        pred.setIsDeleted(DelFlagEnum.UNDEL.getNo());
        pred.setPremisesId(cp.getPremisesId());
        pred.setAgentCompanyId(cp.getStaffCompanyId());
        List<PremisesRelationExternal> relationExternals = premisesRelationExternalService.selectListByDto(pred);
        if (relationExternals == null || relationExternals.size() == 0) {
            return;
        }
        //获取报备绑定关系
        ReportExternalDto reportExternalDto = new ReportExternalDto();
        reportExternalDto.setReportId(cp.getId());
        reportExternalDto.setIsDeleted(DelFlagEnum.UNDEL.getNo());
        List<ReportExternal> list = reportExternalService.selectListByDto(reportExternalDto);
        if (list == null || list.size() == 0) {
            return;
        }
        PartnerInfo partnerInfo = partnerInfoService.selectById(cp.getStaffId());
        apiLogDtoReport.setOtherRelationId(Long.toString(list.get(0).getReportId()));
        if (null != partnerInfo) {
            apiLogDtoReport.setPartnerId(partnerInfo.getId());
            apiLogDtoReport.setPartnerName(partnerInfo.getAccountName());

            apiLogDtoFollow.setPartnerId(partnerInfo.getId());
            apiLogDtoFollow.setPartnerName(partnerInfo.getAccountName());
        }

        UpdateFirsthandIntentionAuditStatusReqDto reqDto = new UpdateFirsthandIntentionAuditStatusReqDto();
        if (CustomerStatusEnum.not_visited.getNo().equals(cp.getCustomerStatus())) {
            // 如果当前报备状态为未到访，超时推送给V10的状态为报备无效：8
            reqDto.setAuditStatus("8");
        }else{
            reqDto.setAuditStatus(switchStatus(CustomerStatusEnum.no_valid.getNo()));
        }
        logger.info("asyncReportInvalidForJob cpStatus:{}, dtoAuditStatus:{}, cpid:{}", cp.getCustomerStatus(), reqDto.getAuditStatus(),
                cp.getId());
        reqDto.setOldAuditStatus(switchStatus(cp.getCustomerStatus()));
        reqDto.setIntentionUuid(list.get(0).getReportUuid());
        reqDto.setCompanyUuid(otherCompanyList.get(0).getCompanyUuid());
        reqDto.setAppkey(otherCompanyList.get(0).getAppkey());
        reqDto.setAppId(otherCompanyList.get(0).getAppid());
        reqDto.setRemark("报备超时未到访或未交易，转为无效报备");
        try {
            String result = HttpApi.doPostV10(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.updateFirsthandIntentionAuditStatus, JSONObject.toJSONString(reqDto), otherCompanyList.get(0).getAppid(), otherCompanyList.get(0).getAppkey(), otherCompanyList.get(0).getCompanyUuid(), apiLogDtoReport);
            //添加跟进信息
            SyncFollowAndAffixReqDto syncReqDto = new SyncFollowAndAffixReqDto();
            V10IntentionFollowDto followVo = new V10IntentionFollowDto();
            followVo.setIntentionUuid(list.get(0).getReportUuid());
            followVo.setOperationType("6");
            followVo.setRemark("报备超时未到访或未交易，转为无效报备");
            followVo.setOldAuditStatus(cp.getCustomerStatus());
            followVo.setNewAuditStatus(CustomerStatusEnum.no_valid.getNo());
            syncReqDto.setFollowVo(followVo);

            String syncFollowAndAffixResult = HttpApi.doPostV10(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.syncFollowAndAffix, JSONObject.toJSONString(syncReqDto), otherCompanyList.get(0).getAppid(), otherCompanyList.get(0).getAppkey(), otherCompanyList.get(0).getCompanyUuid(), apiLogDtoFollow);

        } catch (Exception e) {
            logger.error("报备交易状态异常：{}", e);
            apiLogDtoReport.setRequestContent(JSONObject.toJSONString(reqDto));
            //日志类型
            apiLogDtoReport.setBusinessType(ApiActionEnum.REPORT_AUDIT_NO.getNo());
            apiLogDtoReport.setContent(e.getMessage());
            apiLogDao.create(apiLogDtoReport);
        }

    }


    /**
     * 设置楼盘请求参数
     *
     * @param dto
     * @return
     */
    private SaveFirsthandEstateReqDto setSaveFirstHandEstateDto(Premises dto) {
        SaveFirsthandEstateReqDto returnDto = new SaveFirsthandEstateReqDto();
        // 查询楼盘推荐人
        List<SyncIntentionRecommenderReqDto> premisesRecommenderDtoList = premisesRecommenderService.selectListForIntentionRecommender(dto.getId());
        if (CollectionUtils.isNotEmpty(premisesRecommenderDtoList)) {
            //楼盘推荐人推送
            returnDto.setRecommenders(premisesRecommenderDtoList);
        } else {
            returnDto.setRecommenders(null);
        }
        // 1.楼盘基础信息
        //楼盘uuid
        returnDto.setEstateUuid(dto.getEstateUuid());
        //楼盘名称
        returnDto.setEstateName(dto.getName());
        //楼盘地址
        returnDto.setAddress(dto.getPremisesAddress());
        //省、市、区
        if (dto.getProvinceId() != null) {
            returnDto.setProvince(areaService.selectById(dto.getProvinceId()).getName());
        }
        if (dto.getCityId() != null) {
            returnDto.setCity(areaService.selectById(dto.getCityId()).getName());
        }
        if (dto.getAreaId() != null) {
            returnDto.setArea(areaService.selectById(dto.getAreaId()).getName());
        }

        //楼盘均价 需求变更改为取最低价
        //returnDto.setAveragePrice(ParseUtils.toFloat(dto.getAveragePrice() == null ? null : dto.getAveragePrice().split("\\,")));
        returnDto.setAveragePrice(ParseUtils.toFloat(dto.getAveragePrice() == null ? null : dto.getAveragePrice().split("\\,")[0]));
        //建筑类型
        if (StringUtils.isNotBlank(dto.getBuildingType())) {
            String ids = dto.getBuildingType();
            if (ids.indexOf(",") != -1) {
                String[] list = dto.getBuildingType().split(",");
                StringBuffer sb = new StringBuffer();
                for (String id : list) {
                    String name = AbroadBuildingTypeEnum.getByNo(id).getDes();
                    sb.append(name + ",");
                }
                if (sb.length() > 0) {
                    returnDto.setBuildingType(sb.toString().substring(0, sb.toString().length() - 1));
                }
            } else {
                returnDto.setBuildingType(AbroadBuildingTypeEnum.getByNo(ids).getDes());
            }
        }

        //现金奖
        returnDto.setCashPrize(ParseUtils.toFloat(dto.getDealAward()));
        //渠道楼盘id
        returnDto.setChannelPremises(dto.getId());
        //交房日期(无对应数据)

        //佣金模式 （1:比例，2：金额）
        if (StringUtils.isNotBlank(dto.getCommission())) {
            List<CommissionType> commissions = new ArrayList<>();
            JSONArray jsonArray = JSONObject.parseArray(dto.getCommission());
            if (jsonArray.size() > 0) {
                for (int ii = 0; ii < jsonArray.size(); ii++) {
                    CommissionType commissionType = new CommissionType();
                    JSONObject jsonObject = jsonArray.getJSONObject(ii);
                    commissionType.setName(jsonObject.getString("name"));
                    if ("元".equals(jsonObject.getString("type"))) {
                        commissionType.setType("2");
                    } else if ("%".equals(jsonObject.getString("type"))) {
                        commissionType.setType("1");
                    } else {
                        commissionType.setType("3");
                    }
                    commissionType.setMoney(jsonObject.getString("typeValue"));
                    commissions.add(commissionType);
                }
            }
            returnDto.setCommissions(commissions);
        }

        //结佣方式
        if (dto.getCommissionWay() != null) {
            returnDto.setCommissionWay(CommissionWayEnum.getDescByNo(dto.getCommissionWay()));
        }
        //公司uuid
//        returnDto.setCompanyUuid(commpanyUuid);
        //带看确认方式（不需要）
        // 合同有效终止日期 todo 需要修改
        returnDto.setContractStartDate(dto.getCooperationBeginTime());
        // 合同有效开始日期
        returnDto.setContractEndDate(dto.getCooperationEndTime());
        //合作规则
        returnDto.setCooRule(dto.getCooperationRule());
        //创建人，人员部门1/2/3 不需要
//        returnDto.setEmployeeUuid1("5d05ed0d-cd93-49d4-a909-43dc88fda103");
//        returnDto.setDeptUuid1("1d10466757204c94854525822a76e9f5");
        //开发商 company_id
        returnDto.setDevelopers(dto.getBuildingCompany());
        //商圈 不需要
        //地下车位
        returnDto.setDownCarPort(ParseUtils.toInteger(dto.getDownCarPort()));
        //参考首付 不需要
        //项目人员1/2/3 不需要
        //项目描述
        returnDto.setEstateDesc(dto.getIntroduction());
        //楼盘名称
        returnDto.setEstateName(dto.getName());
        //项目特色
        returnDto.setFeatureType(getFeatureType(dto.getCodeName()));
        //绿化率
        returnDto.setGreeningRate(ParseUtils.toFloat(dto.getGreeningRate()));
        //是否主推 （0普通 1主推 默认0）
        returnDto.setHotStatus("0");
        //规划户数
        returnDto.setHouseHolds(ParseUtils.toInteger(dto.getHouseHolds()));
        //报备保护天数类型 以前为分钟
        returnDto.setIntentionIntervalType(StringUtils.isBlank(dto.getVisitProtectType()) ? "3" : dto.getVisitProtectType());
        //报备保护时间
        if (dto.getSaveDaysType() == null || TimeUnitTypeEnum.NONE.getNo().equals(dto.getSaveDaysType().toString())) {
            returnDto.setIntentionInterval(ParseUtils.toInteger(dto.getVisitProtect()));
        } else {
            returnDto.setIntentionInterval(0);
        }
//        returnDto.setIntentionInterval(ParseUtils.toInteger(dto.getVisitProtect()));
        //报备接受方式 不需要
        //发布状态 不需要
        // 渠道状态 默认在 审核通过之后才推楼盘信息 所以上下架状态都为0:上架
        if (SaleStatusEnum.type_3.getNo().equals(dto.getSaleStatus())) {
            returnDto.setChannelIssuedStatus(ShelvesStatusEnum.type0.getNo());
        } else {
            returnDto.setChannelIssuedStatus(ShelvesStatusEnum.type1.getNo());
        }

        // 物业公司
        returnDto.setManageCompany(dto.getPropertyCompany());
        //楼盘最高、最低价 不需要
        //报备号码 1,2,3(全号、前三后四、前四后三)
        returnDto.setMobileRule("1");
        //参考月供 不需要
        //开盘日期
        returnDto.setOpenDate(dto.getOpeningTime());
        //其他佣金模式说明，其他结佣说明，其他确认方式描述 不需要
        returnDto.setPlotRatio(ParseUtils.toFloat(dto.getPlotRatio()));
        //委托方负责人 （现改为对接人电话）
        returnDto.setClientPrincipal(dto.getManager());
        // 手机号 项目经理联系方式 (现改为对接人)
        returnDto.setPrincipalMobile(dto.getMobile());
        // 物业费用
        returnDto.setPropertyFee(ParseUtils.toFloat(dto.getPropertyCharges()));
        // 产权年限
        if (StringUtils.isNotBlank(dto.getRightYears())) {
            returnDto.setPropertyRight(dto.getRightYears() + "年");
        }
        // 物业类型 渠道仅为单选
        if (StringUtils.isNotEmpty(dto.getEstateType())) {
            String[] estateTypes = dto.getEstateType().split(",");
            StringBuilder sb = new StringBuilder();
            for (String et : estateTypes) {
                sb.append(EstateTypeEnum.getByNo(et).getDes() + ",");
            }
            if (sb.length() > 0) {
                sb.deleteCharAt(sb.length() - 1);
            }
            returnDto.setPropertyType(sb.toString());
        }
        // 备注
        returnDto.setRemark(dto.getRemark());
        // 销售进度
        returnDto.setSaleStatus(switchPremisesStatus(dto.getSaleStatus()));
        // 最短报备时间
        returnDto.setShortestInterval(ParseUtils.toInteger(dto.getSpecialTime()));
        // 周边配套 交通状况 不需要
        //地上车位
        returnDto.setUpCarPort(ParseUtils.toInteger(dto.getUpCarPort()));
        // 到场保护时间：天
        if (dto.getSaveDaysType() == null || TimeUnitTypeEnum.NONE.getNo().equals(dto.getSaveDaysType().toString())) {
            returnDto.setVisitInterval(ParseUtils.toInteger(dto.getSaveDays()));
        } else {
            returnDto.setVisitInterval(0);
        }
        // 楼盘带看奖
        returnDto.setVisitPrize(ParseUtils.toFloat(dto.getReward()));
        // 楼盘类型 1 渠道王  2 非渠道王
        returnDto.setEstateType("1");
        // 楼盘创建日期
        returnDto.setChannelCreateDate(dto.getCreateTime());
        // 楼盘更新日期
        returnDto.setChannelUpdateDate(dto.getUpdateTime());
        // 楼盘发布状态更改日期
        returnDto.setIssueStatusChangeDate(new Date());
        //交房日期
        returnDto.setCheckOutDate(dto.getCheckInTime());
        // 楼盘图片,户型图，户型
        Map<String, List> map = setPreimsesImage(dto.getId(), dto.getUrl());
        returnDto.setImages(map.get("PremisesImage"));
        returnDto.setHouseTypes(map.get("HouseType"));
        // 是否有推荐人
        returnDto.setHasRecommender(StringUtils.isBlank(dto.getHasRecommender()) ? "0" : dto.getHasRecommender());
        //商圈
//        returnDto.setDistrict("长江三角洲");
        returnDto.setPanoramicView(dto.getPanoramicView());

        return returnDto;
    }

    /**
     * 设置图片，户型
     *
     * @param premiesiseId
     * @param coverImageUrl
     * @return
     */
    private Map<String, List> setPreimsesImage(Long premiesiseId, String coverImageUrl) {
        Map<String, List> map = new HashMap<>();
        List<PremisesImageV10Dto> list = new ArrayList<>();
        List<HouseType> houseTypes = new ArrayList<>();
        // 封面
        PremisesImageV10Dto coverImage = new PremisesImageV10Dto();
        coverImage.setChannelImageId(premiesiseId);
        coverImage.setBackUpFlag(false);
        coverImage.setImageType("1");
        coverImage.setImageDesc("封面图");
        coverImage.setImageUrl(coverImageUrl);
        list.add(coverImage);
        //1 查询楼盘相册
        PremisesImageDto imageDto = new PremisesImageDto();
        imageDto.setPremisesId(premiesiseId);
        imageDto.setIsDeleted(DelFlagEnum.UNDEL.getNo());
        List<PremisesImage> imageList = imageMapper.selectListByDto(imageDto);
        for (PremisesImage pi : imageList) {
            PremisesImageV10Dto imageV10Dto = new PremisesImageV10Dto();
            imageV10Dto.setBackUpFlag(false);
//            imageV10Dto.setBusinessUuid();
            imageV10Dto.setImageType(pi.getImageType());
            imageV10Dto.setImageDesc(pi.getImageDesc());
            imageV10Dto.setImageUrl(pi.getImageUrl());
            imageV10Dto.setChannelImageId(pi.getId());

            list.add(imageV10Dto);
        }
        // 2 户型图
        ApartmentLayoutDiagramDto aldDto = new ApartmentLayoutDiagramDto();
        aldDto.setPremisesId(premiesiseId);
        aldDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        List<ApartmentLayoutDiagram> aldList = apartmentLayoutDiagramMapper.selectListByDto(aldDto);
        for (ApartmentLayoutDiagram ald : aldList) {
            // 图片 户型图 图片不在传到图片列表 直接放到对应户型
            //设置户型
            HouseType ht = new HouseType();
            ht.setBuildingArea(ParseUtils.toFloat(ald.getArea().split("\\,")));
            ht.setDecorate(ald.getDecoration());
            ht.setFamilyStructure(ald.getHouseStruct());
            ht.setHouseTypeName(ald.getHuxingName());
            ht.setChannelHouseTypeId(ald.getId());
            ht.setOrientation(ald.getOrientations());
            // 户型均价， 需求变更改为取最低值
            ht.setSellingPrice(ParseUtils.toFloat(ald.getAveragePrice() == null ? null : ald.getAveragePrice().toString().split("\\,")[0]));
            ht.setRemark(ald.getRemark());
            ht.setImageName(ald.getHuxingName());
            ht.setImageUrl(ald.getUrl());
            if(StringUtils.isNotBlank(ald.getUrl())){
                String[] urlArr = ald.getUrl().split(";");
                if(urlArr.length > 0){
                    ht.setImageUrl(urlArr[0]);
                }
            }
            //室、厅、卫厨、阳台
            String[] layout = getApartments(ald.getApartmentLayout());
            if (layout != null) {
                ht.setBedroom(layout.length > 0 ? layout[0] : null);
                ht.setDrawingRoom(layout.length > 1 ? layout[1] : null);
                ht.setToilet(layout.length > 2 ? layout[2] : null);
                ht.setVeranda(layout.length > 3 ? layout[3] : null);

            }
            houseTypes.add(ht);
        }
        map.put("PremisesImage", list);
        map.put("HouseType", houseTypes);


        return map;
    }

    /**
     * 设置户型
     *
     * @param aprtment
     * @return
     */
    private String[] getApartments(String aprtment) {
        String[] returnStrings = new String[4];
        String[] s = aprtment.split("室");
        if (s.length > 0) {
            returnStrings[0] = s[0].equals("无卧") ? "0" : s[0];
            if (s.length == 1) {
                return returnStrings;
            }
        }
        String[] t = s[1].split("厅");
        if (s.length > 0) {
            returnStrings[1] = t[0].equals("无") ? "0" : t[0];
            if (t.length == 1) {
                return returnStrings;
            }
        }
        String[] w = t[1].split("卫");
        if (w.length > 0) {
            returnStrings[2] = w[0].equals("无") ? "0" : w[0];
            if (w.length == 1) {
                return returnStrings;
            }
        }
        String[] yt = w[1].length() > 3 ? w[1].substring(w[1].length() - 3, w[1].length()).split("阳台") : w[1].split("阳台");
        if (yt.length > 0) {
            returnStrings[3] = yt[0].equals("无") ? "0" : yt[0];
            return returnStrings;
        }

        return null;
    }

    /**
     * 项目特色 来源于项目标签
     *
     * @return
     */
    private String getFeatureType(String codeName) {
        // 查询所有标签
        // 楼盘标签
        if (StringUtils.isNotEmpty(codeName)) {
            String[] labels = codeName.split(",");
            if (labels.length > 0) {
                List<Long> lableList = new ArrayList<Long>();
                for (String b : labels) {
                    lableList.add(Long.parseLong(b));
                }
                List<BaseCodeValue> codes = baseCodeValueService.selectWithIds(lableList);
                StringBuilder sbCodes = new StringBuilder();
                for (BaseCodeValue bcv : codes) {
                    sbCodes.append(bcv.getCodeName() + ",");
                }
                return sbCodes.substring(0, sbCodes.lastIndexOf(","));
            }
        }

        return null;
    }

    /**
     * 状态转换 V10 审核状态:   1：无效  2：待审   3：未到访      4：已到访
     * 渠道 审核状态： 0：待审  6：已到访  10：未到访     -1：无效 需要转换
     *
     * @param status
     * @return
     */
    private String switchStatus(String status) {
        Map<String, String> statusMap = new HashMap<String, String>() {{
            put("0", "2");//待审
            put("6", "4");//已到访
            put("10", "3");//未到访
            put("-1", "1");//无效
        }};
        String returnStatus = statusMap.get(status);
        if (returnStatus == null) {
            throw new RuntimeException("未找到对应的状态");
        }
        return returnStatus;
    }

    /**
     * 渠道楼盘销售状态转换V10 楼盘状态
     *
     * @param status
     * @return
     */
    public String switchPremisesStatus(String status) {
        Map<String, String> statusMap = new HashMap<String, String>() {
            {
                put("0", "1");//待售
                put("1", "3");//在售
                put("2", "6");//售罄
                // 以下状态未使用
                put("3", "");//在售期房
                put("4", "");//认筹中
                put("5", "");// 尾盘
            }
        };
        String returnStatus = statusMap.get(status);
        if (StringUtils.isEmpty(returnStatus)) {
            return "";
        }
        return returnStatus;
    }

    private SyncIntentionReqDto setSyncIntention(CustomerPremises cp, PremisesRelationExternal premisesRelationExternal, OtherSysUserDto otherSysUserDto) {
        SyncIntentionReqDto reqDto = new SyncIntentionReqDto();
        reqDto.setEstateUuid(premisesRelationExternal.getExternalId());
        reqDto.setCustomerName(cp.getName());
        reqDto.setCustomerMobile(cp.getMobile());
        reqDto.setMobileRule(cp.getMobile().contains(StringConstant.THREE_STAR) ? "2" : "1");
        reqDto.setEmployeeUuid(otherSysUserDto.getOtherUserId());
        reqDto.setEmployeeMobile(otherSysUserDto.getUserPhone());
        reqDto.setEmployeeName(otherSysUserDto.getUserName());
        reqDto.setVisitCount("1");//到访人数
        reqDto.setVisitWay("1");//到访方式
        reqDto.setGender(cp.getGender());
        reqDto.setVisitTime(DateUtils.DateToString(cp.getHopeVisitTime(), DateStyle.YYYY_MM_DD_HH_MM_SS));
        reqDto.setRemark(cp.getRemark());
        reqDto.setReportPeriodTime(DateUtils.DateToString(cp.getReportPeriodTime(), DateStyle.YYYY_MM_DD_HH_MM_SS));
        return reqDto;
    }

    //添加到报备关联表中
    private ReportExternal addReportRelation(CustomerPremises cp, String reportUuid, String premisesUuid) {
        ReportExternalDto red = new ReportExternalDto();
        red.setReportId(cp.getId());
        red.setReportUuid(reportUuid);
        red.setPremiseId(cp.getPremisesId());
        red.setPremisesUuid(premisesUuid);
        red.setSysId("1");
        red.setIsDeleted(DelFlagEnum.UNDEL.getNo());
        return reportExternalService.create(red);
    }

    @Override
    public PremisesIntentionResDto queryIntentionStatus(String intentionUuid, String sysId) {
        PremisesIntentionResDto resDto = new PremisesIntentionResDto();
        ReportExternal reportExternal = reportExternalMapper.getReportExternal(intentionUuid, sysId);
        if (reportExternal == null) {
            resDto.setResultMsg("无报备关联关系");
            resDto.setResult(ResultEnum.FAIL.getNo());
            return resDto;
        }
        CustomerPremises customerPremises = customerPremisesMapper.selectById(reportExternal.getReportId());
        if (customerPremises == null) {
            resDto.setResultMsg("找不到该报备信息");
            resDto.setResult(ResultEnum.FAIL.getNo());
            return resDto;
        }
        resDto.setIntentionUuid(intentionUuid);
        resDto.setAuditStatus(customerPremises.getCustomerStatus());
        resDto.setTradeStatus(customerPremises.getConfirmStatus());
        resDto.setResult(ResultEnum.SUCCESS.getNo());
        return resDto;
    }

    @Override
    @Async
    public void asyncV10PushEmployeeInfo(Map<String, List<V10EmployeeInfoDto>> map) {
        if (MapUtils.isNotEmpty(map)) {
            OtherCompanyDto ocDto = new OtherCompanyDto();
            for (String key : map.keySet()) {
                ocDto.setCompanyUuid(key);
                List<OtherCompany> otherCompanys = otherCompanyDao.selectListByDto(ocDto);
                if (CollectionUtils.isNotEmpty(otherCompanys) && CollectionUtils.isNotEmpty(map.get(key))) {
                    OtherCompany o = otherCompanys.get(0);
                    this.pushV10(map.get(key), o);
                }
            }

        }
    }

    private void pushV10(List<V10EmployeeInfoDto> employeeInfoDtos, OtherCompany oc) {
        try {
            ApiLogDto apiLog = new ApiLogDto();
            apiLog.setCompanyId(oc.getChannelCompanyId());
            apiLog.setOtherCompanyId(oc.getCompanyUuid());
            apiLog.setBusinessType(ApiActionEnum.EMPLOYEE_INFO.getNo());
            apiLog.setBusinessTime(new Date());
            V10EmployeeInfoReqDto reqDto = new V10EmployeeInfoReqDto();
            reqDto.setData(employeeInfoDtos);
            //请求接口
            String result = HttpApi.doPostV10(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.syncPushEmployeeInfo, JSONObject.toJSONString(reqDto), oc.getAppid(), oc.getAppkey(), oc.getCompanyUuid(), apiLog);
        } catch (Exception e) {
            logger.error("经纪人信息同步调用失败: {}", e);
            apiLogDao.addApiLog(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.syncPushEmployeeInfo, e.getMessage(), "经纪人信息同步调用失败");
        }
    }

    /**
     * @param premisesId  源楼盘ID
     * @param premisesIds 批量推送楼盘ID
     */
    @Override
    @Async
    public void batchPushReportModel(Long premisesId, List<Long> premisesIds) {
        Premises premises = premisesService.selectSimpleById(premisesId);
        List<OtherCompany> listOtherCompany = otherCompanyDao.getV10CompanyListByCompanyId(premises.getCompanyId());
        if (CollectionUtils.isEmpty(listOtherCompany)) {
            logger.info("批量推送楼盘报备模板失败，listOtherCompany is null: {}", premises.getCompanyId());
            return;
        }
        // 获取当前楼盘的模板信息
        ReportModelDto selectReportModel = new ReportModelDto();
        selectReportModel.setDelFlag(DelFlagEnum.UNDEL.getNo());
        selectReportModel.setPremisesId(premisesId);
        selectReportModel.setModelType(ModelTypeEnum.customer_config.getCode());
        List<ReportModel> list = reportModelService.selectListByDto(selectReportModel);
        Optional.ofNullable(premisesIds).orElseGet(ArrayList::new);
        premisesIds.add(premisesId);
        if (CollectionUtils.isEmpty(list)) {
            logger.info("批量推送楼盘报备模板为空，batchPushReportModel is null: {}", premisesId);
            // 推送空的楼盘模板信息
            pushEmptyModelColumn(premises, listOtherCompany, premisesIds);
            return;
        }

        List<PremisesReportModelDto> modelColumn = list.stream().map(item -> {
            PremisesReportModelDto prmd = new PremisesReportModelDto();
            prmd.setModelId(item.getId());
            prmd.setModelColumn(item.getModelColumn());
            return prmd;
        }).collect(Collectors.toList());
        // 构建推送V10模板对象

        for (OtherCompany oc : listOtherCompany) {
            ReportModelV10Dto reportModelV10Dto = new ReportModelV10Dto();
            // 获取需要批量推送的楼盘外部关联数据
            PremisesRelationExternalDto entity = new PremisesRelationExternalDto();
            entity.setPremisesIds(premisesIds);
            entity.setExternalCompanyId(oc.getCompanyUuid());
            List<PremisesRelationExternal> preList = premisesRelationExternalService.selectListByDto(entity);
            if (CollectionUtils.isEmpty(preList)) {
                logger.info("楼盘外部关联关系为空，PremisesRelationExternal is null: {}", oc.getCompanyUuid());
                continue;
            }
            List<String> estateUuids = preList.stream().map(item -> item.getExternalId()).collect(Collectors.toList());
            reportModelV10Dto.setEstateUuids(estateUuids);
            reportModelV10Dto.setModelColumn(modelColumn);
            try {
                ApiLogDto apiLog = new ApiLogDto();
                apiLog.setCompanyId(premises.getCompanyId());
                apiLog.setOtherCompanyId(oc.getCompanyUuid());
                apiLog.setBusinessType(ApiActionEnum.PREMISES_REPORT_MODEL.getNo());
                apiLog.setBusinessTime(new Date());
                logger.info("push data : {}", JSONObject.toJSONString(reportModelV10Dto));
                //请求接口
                HttpApi.doPostV10(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.syncMouldField, JSONObject.toJSONString(reportModelV10Dto), oc.getAppid(), oc.getAppkey(), oc.getCompanyUuid(), apiLog);
            } catch (Exception e) {
                logger.error("推送楼盘报备模板调用失败: {}", e);
                apiLogDao.addApiLog(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.syncMouldField, e.getMessage(), "推送楼盘报备模板异步调用失败");
            }
        }
    }

    /**
     *  推送空的楼盘模板信息
     * @param premises          楼盘信息
     * @param listOtherCompany  外部关联信息
     * @param premisesIds       楼盘ID信息
     */
    private void pushEmptyModelColumn(Premises premises, List<OtherCompany> listOtherCompany, List<Long> premisesIds){
        for (OtherCompany oc : listOtherCompany) {
            PremisesRelationExternalDto entity = new PremisesRelationExternalDto();
            entity.setPremisesIds(premisesIds);
            entity.setExternalCompanyId(oc.getCompanyUuid());
            List<PremisesRelationExternal> preList = premisesRelationExternalService.selectListByDto(entity);
            if (CollectionUtils.isEmpty(preList)) {
                logger.info("楼盘外部关联关系为空，PremisesRelationExternal is null: {}", oc.getCompanyUuid());
                continue;
            }
            List<String> estateUuids = preList.stream().map(item -> item.getExternalId()).collect(Collectors.toList());
            List<PremisesReportModelDto> modelColumn = new ArrayList<>();
            ReportModelV10Dto reportModelV10Dto = new ReportModelV10Dto();

            reportModelV10Dto.setEstateUuids(estateUuids);
            reportModelV10Dto.setModelColumn(modelColumn);
            try {
                ApiLogDto apiLog = new ApiLogDto();
                apiLog.setCompanyId(premises.getCompanyId());
                apiLog.setOtherCompanyId(oc.getCompanyUuid());
                apiLog.setBusinessType(ApiActionEnum.PREMISES_REPORT_MODEL.getNo());
                apiLog.setBusinessTime(new Date());
                logger.info("push empty data : {}", JSONObject.toJSONString(apiLog));
                //请求接口
                HttpApi.doPostV10(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.syncMouldField, JSONObject.toJSONString(reportModelV10Dto), oc.getAppid(), oc.getAppkey(), oc.getCompanyUuid(), apiLog);
            } catch (Exception e) {
                logger.error("楼盘报备同步调用失败: {}", e);
                apiLogDao.addApiLog(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.syncPushEmployeeInfo, e.getMessage(), "楼盘报备同步调用失败");
            }
        }

    }

    @Override
    public BaseResponseDto syncChannelIntentionStatus(SyncChannelIntentionStatusDTO reqDto) {
        BaseResponseDto brDto = new BaseResponseDto();
        ApiLogDto apiLogDto = new ApiLogDto();
        if (StringUtils.isBlank(reqDto.getIntentionUuid()) || StringUtils.isBlank(reqDto.getStatus())) {
            logger.info("报备重置,推送数据不完善: {}", JSONObject.toJSONString(reqDto));
            brDto.setResponseMessage("推送数据不完善,不能为空");
            return brDto;
        }
        try {
            //获取报备绑定关系
            ReportExternalDto reportExternalDto = new ReportExternalDto();
            reportExternalDto.setReportUuid(reqDto.getIntentionUuid());
            reportExternalDto.setIsDeleted(DelFlagEnum.UNDEL.getNo());
            List<ReportExternal> list = reportExternalService.selectListByDto(reportExternalDto);

            if (CollectionUtils.isEmpty(list)) {
                logger.info("报备与Saas无绑定关系,无需推送: {}", reqDto.getIntentionUuid());
                brDto.setResponseMessage("报备与Saas无绑定关系,无需推送");
                return brDto;
            }

            //根据报备获取绑定楼盘
            PremisesRelationExternalDto preDto = new PremisesRelationExternalDto();
            preDto.setExternalId(list.get(0).getPremisesUuid());
            preDto.setIsDeleted(DelFlagEnum.UNDEL.getNo());
            List<PremisesRelationExternal> premisesRelationList = premisesRelationExternalService.selectListByDto(preDto);
            if (premisesRelationList == null || premisesRelationList.size() == 0) {
                logger.info("报备所属楼盘与Saas无绑定关系: {}", list.get(0).getPremisesUuid());
                brDto.setResponseMessage("报备所属楼盘与Saas无绑定关系,无需推送");
                return brDto;
            }
            //根据楼盘获取绑定公司
            OtherCompanyDto otherCompany = new OtherCompanyDto();
            otherCompany.setIsDeleted(DelFlagEnum.UNDEL.getNo());
            otherCompany.setCompanyUuid(premisesRelationList.get(0).getExternalCompanyId());
            List<OtherCompany> otherCompanyList = otherCompanyDao.selectListByDto(otherCompany);
            if (otherCompanyList == null || otherCompanyList.size() == 0) {
                logger.info("报备所属公司与Saas无绑定关系: {}", premisesRelationList.get(0).getExternalCompanyId());
                brDto.setResponseMessage("报备所属公司与Saas无绑定关系,无需推送");
                return brDto;
            }
            //日志参数
            apiLogDto.setOtherCompanyId(otherCompanyList.get(0).getCompanyUuid());
            Premises premises = premisesService.getSimpleById(premisesRelationList.get(0).getPremisesId());
            if (null != premises) {
                apiLogDto.setCompanyId(premises.getCompanyId());
                apiLogDto.setPremisesId(premises.getId());
                apiLogDto.setPremisesName(premises.getName());
            }
            //报备及人员信息
            CustomerPremises customerPremises = customerPremisesService.selectById(list.get(0).getReportId());
            PartnerInfo partnerInfo = partnerInfoService.selectById(customerPremises.getStaffId());
            apiLogDto.setOtherRelationId(Long.toString(list.get(0).getReportId()));
            if (null != partnerInfo) {
                apiLogDto.setPartnerId(partnerInfo.getId());
                apiLogDto.setPartnerName(partnerInfo.getAccountName());
            }
            //日志类型
            apiLogDto.setBusinessType(ApiActionEnum.REPORT_RESET.getNo());
            // 报备审核,转换状态至V10状态
            if ("1".equals(reqDto.getChannelStatusType())) {
                reqDto.setStatus(switchStatus(reqDto.getStatus()));
            }
            String result = HttpApi.doPostV10(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.syncChannelIntentionStatus, JSONObject.toJSONString(reqDto), otherCompanyList.get(0).getAppid(), otherCompanyList.get(0).getAppkey(), otherCompanyList.get(0).getCompanyUuid(), apiLogDto);
            logger.info("巧渠道调用syncChannelIntentionStatus后的返回结果: {}", result);

            brDto = JSONObject.parseObject(result, BaseResponseDto.class);

            if (!"1".equals(brDto.getResponseCode())) {
                //调用失败
                brDto.setResponseCode(ResultEnum.FAIL.getNo());
                brDto.setResponseMessage("同步交易状态失败！");
                return brDto;
            }
        } catch (Exception e) {
            logger.error("报备交易状态异常：{}", e);
            apiLogDto.setRequestContent(JSONObject.toJSONString(reqDto));
            apiLogDto.setBusinessType(ApiActionEnum.REPORT_RESET.getNo());
            apiLogDto.setContent(e.getMessage());
            apiLogDao.create(apiLogDto);
            apiLogDao.addApiLog(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.syncChannelIntentionStatus, e.getMessage(),"报备交易状态同步异常");
        }
        return brDto;
    }

    @Override
    public BaseResponseDto exchangeHouses(UpdateFirsthandIntentionTradeStatusReqDto reqDto, SyncFollowAndAffixReqDto syncReqDto) {
        BaseResponseDto brDto = new BaseResponseDto();
        ApiLogDto apiLogDto = new ApiLogDto();
        if (reqDto.getIntentionUuid() == null) {
            brDto.setResponseMessage("报备uuid不能为空");
            return brDto;
        }
        if (reqDto.getTradeStatus() == null) {
            brDto.setResponseMessage("交易状态不能为空");
        }
        try {
            //获取报备绑定关系
            ReportExternalDto reportExternalDto = new ReportExternalDto();
            reportExternalDto.setReportUuid(reqDto.getIntentionUuid());
            reportExternalDto.setIsDeleted(DelFlagEnum.UNDEL.getNo());
            List<ReportExternal> list = reportExternalService.selectListByDto(reportExternalDto);

            if (list == null || list.size() == 0) {
                throw new RuntimeException("未获取报备信息");
            }

            //根据报备获取绑定楼盘
            PremisesRelationExternalDto preDto = new PremisesRelationExternalDto();
            preDto.setExternalId(list.get(0).getPremisesUuid());
            preDto.setIsDeleted(DelFlagEnum.UNDEL.getNo());
            List<PremisesRelationExternal> premisesRelationList = premisesRelationExternalService.selectListByDto(preDto);
            if (premisesRelationList == null || premisesRelationList.size() == 0) {
                throw new RuntimeException("报备相关楼盘信息为空");
            }
            //根据楼盘获取绑定公司
            OtherCompanyDto otherCompany = new OtherCompanyDto();
            otherCompany.setIsDeleted(DelFlagEnum.UNDEL.getNo());
            otherCompany.setCompanyUuid(premisesRelationList.get(0).getExternalCompanyId());
            List<OtherCompany> otherCompanyList = otherCompanyDao.selectListByDto(otherCompany);
            if (otherCompanyList == null || otherCompanyList.size() == 0) {
                apiLogDto.setRequestContent(JSONObject.toJSONString(reqDto));
                apiLogDto.setBusinessType(ApiActionEnum.EXCHANGE_HOUSES.getNo());
                apiLogDto.setContent("公司相关信息为空,未发送请求");
                apiLogDao.create(apiLogDto);
                return brDto;
            }
            //日志参数
            apiLogDto.setOtherCompanyId(otherCompanyList.get(0).getCompanyUuid());
            Premises premises = premisesService.getSimpleById(premisesRelationList.get(0).getPremisesId());
            if (null != premises) {
                apiLogDto.setCompanyId(premises.getCompanyId());
                apiLogDto.setPremisesId(premises.getId());
                apiLogDto.setPremisesName(premises.getName());
            }
            //报备及人员信息
            CustomerPremises customerPremises = customerPremisesService.selectById(list.get(0).getReportId());
            apiLogDto.setPartnerId(customerPremises.getStaffId());
            apiLogDto.setPartnerName(customerPremises.getStaffPhone());
            //日志类型
            apiLogDto.setBusinessType(ApiActionEnum.EXCHANGE_HOUSES.getNo());
            String result = HttpApi.doPostV10(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.updateFirsthandEstateSaleStatus, JSONObject.toJSONString(reqDto), otherCompanyList.get(0).getAppid(), otherCompanyList.get(0).getAppkey(), otherCompanyList.get(0).getCompanyUuid(), apiLogDto);

            logger.info("巧渠道调用syncExchangeHouses后的换房返回结果" + result);
            brDto = JSONObject.parseObject(result, BaseResponseDto.class);
            if (!"1".equals(brDto.getResponseCode())) {
                //调用失败
                brDto.setResponseCode(ResultEnum.FAIL.getNo());
                brDto.setResponseMessage("换房失败！");
                return brDto;
            }

            V10IntentionFollowDto followVo = syncReqDto.getFollowVo();
            followVo.setOldAuditStatus(switchStatus(followVo.getOldAuditStatus()));
            followVo.setNewAuditStatus(switchStatus(followVo.getNewAuditStatus()));
            followVo.setOldTradeStatus(reqDto.getOldTradeStatus());
            followVo.setNewTradeStatus(reqDto.getTradeStatus());
            syncReqDto.setFollowVo(followVo);
            apiLogDto.setBusinessType(ApiActionEnum.EXCHANGE_HOUSES.getNo());
            result = HttpApi.doPostV10(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.syncFollowAndAffix, JSONObject.toJSONString(syncReqDto), otherCompanyList.get(0).getAppid(), otherCompanyList.get(0).getAppkey(), otherCompanyList.get(0).getCompanyUuid(), apiLogDto);

            logger.info("巧渠道调用syncFollowAndAffix后的换房返回结果" + result);
            brDto = JSONObject.parseObject(result, BaseResponseDto.class);
            if (!"1".equals(brDto.getResponseCode())) {
                //调用失败
                brDto.setResponseCode(ResultEnum.FAIL.getNo());
                brDto.setResponseMessage("换房同步跟进和附件失败！");
                return brDto;
            }

        } catch (Exception e) {
            logger.error("换房异常：{}", e);
            apiLogDto.setRequestContent(JSONObject.toJSONString(reqDto));
            //日志类型
            apiLogDto.setBusinessType(ApiActionEnum.EXCHANGE_HOUSES.getNo());
            apiLogDto.setContent(e.getMessage());
            apiLogDao.create(apiLogDto);
        }
        return brDto;
    }

    @Override
    @Async
    public BaseResponseDto updateFirsthandIntentionRevisit(FirsthandIntentionRevisitReqDto reqDto, SyncFollowAndAffixReqDto syncReqDto) {
        BaseResponseDto brDto = new BaseResponseDto();
        ApiLogDto apiLogDto = new ApiLogDto();
        if (reqDto.getIntentionUuid() == null) {
            brDto.setResponseMessage("报备uuid不能为空");
            return brDto;
        }
        try {
            //获取报备绑定关系
            ReportExternalDto reportExternalDto = new ReportExternalDto();
            reportExternalDto.setReportUuid(reqDto.getIntentionUuid());
            reportExternalDto.setIsDeleted(DelFlagEnum.UNDEL.getNo());
            List<ReportExternal> list = reportExternalService.selectListByDto(reportExternalDto);
            if (list == null || list.size() == 0) {
                throw new RuntimeException("未获取报备信息");
            }
            ReportExternal reportExternal = list.get(0);
            //根据报备获取绑定楼盘
            PremisesRelationExternalDto preDto = new PremisesRelationExternalDto();
            preDto.setExternalId(reportExternal.getPremisesUuid());
            preDto.setIsDeleted(DelFlagEnum.UNDEL.getNo());
            List<PremisesRelationExternal> premisesRelationList = premisesRelationExternalService.selectListByDto(preDto);
            if (premisesRelationList == null || premisesRelationList.size() == 0) {
                throw new RuntimeException("报备相关楼盘信息为空");
            }
            //根据楼盘获取绑定公司
            OtherCompanyDto otherCompany = new OtherCompanyDto();
            otherCompany.setIsDeleted(DelFlagEnum.UNDEL.getNo());
            otherCompany.setCompanyUuid(premisesRelationList.get(0).getExternalCompanyId());
            List<OtherCompany> otherCompanyList = otherCompanyDao.selectListByDto(otherCompany);
            if (otherCompanyList == null || otherCompanyList.size() == 0) {
                apiLogDto.setRequestContent(JSONObject.toJSONString(reqDto));
                apiLogDto.setBusinessType(ApiActionEnum.REPORT_REVISIT.getNo());
                apiLogDto.setContent("公司相关信息为空,未发送请求");
                apiLogDao.addApiLog(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.syncChannelIntentionRevisit, "公司相关信息为空,未发送请求", "报备复访同步异常");
                return brDto;
            }
            //日志参数
            apiLogDto.setOtherCompanyId(otherCompanyList.get(0).getCompanyUuid());
            Premises premises = premisesService.getSimpleById(premisesRelationList.get(0).getPremisesId());
            if (null != premises) {
                apiLogDto.setCompanyId(premises.getCompanyId());
                apiLogDto.setPremisesId(premises.getId());
                apiLogDto.setPremisesName(premises.getName());
            }
            //报备及人员信息
            CustomerPremises customerPremises = customerPremisesService.selectById(reportExternal.getReportId());
            PartnerInfo partnerInfo = partnerInfoService.selectById(customerPremises.getStaffId());
            apiLogDto.setOtherRelationId(Long.toString(reportExternal.getReportId()));
            if (null != partnerInfo) {
                apiLogDto.setPartnerId(partnerInfo.getId());
                apiLogDto.setPartnerName(partnerInfo.getAccountName());
            }
            //日志类型
            apiLogDto.setBusinessType(ApiActionEnum.REPORT_REVISIT.getNo());
            String result = HttpApi.doPostV10(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.syncChannelIntentionRevisit, JSONObject.toJSONString(reqDto), otherCompanyList.get(0).getAppid(), otherCompanyList.get(0).getAppkey(), otherCompanyList.get(0).getCompanyUuid(), apiLogDto);

            logger.info("巧渠道调用updateFirsthandIntentionRevisit后的返回结果：{}",result);
            brDto = JSONObject.parseObject(result, BaseResponseDto.class);
            if (!"1".equals(brDto.getResponseCode())) {
                //调用失败
                brDto.setResponseCode(ResultEnum.FAIL.getNo());
                brDto.setResponseMessage("同步报备复访失败！");
                return brDto;
            }

            V10IntentionFollowDto followVo = syncReqDto.getFollowVo();
            followVo.setOldAuditStatus(switchStatus(followVo.getOldAuditStatus()));
            followVo.setNewAuditStatus(switchStatus(followVo.getNewAuditStatus()));
            syncReqDto.setFollowVo(followVo);
            apiLogDto.setBusinessType(ApiActionEnum.FOLLOW_AYS.getNo());
            result = HttpApi.doPostV10(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.syncFollowAndAffix, JSONObject.toJSONString(syncReqDto), otherCompanyList.get(0).getAppid(), otherCompanyList.get(0).getAppkey(), otherCompanyList.get(0).getCompanyUuid(), apiLogDto);

            logger.info("巧渠道调用syncFollowAndAffix后的返回结果：{}",result);
            brDto = JSONObject.parseObject(result, BaseResponseDto.class);
            if (!"1".equals(brDto.getResponseCode())) {
                //调用失败
                brDto.setResponseCode(ResultEnum.FAIL.getNo());
                brDto.setResponseMessage("同步跟进和附件失败！");
                return brDto;
            }
        } catch (Exception e) {
            logger.error("报备复访异常：{}", e);
            apiLogDto.setRequestContent(JSONObject.toJSONString(reqDto));
            //日志类型
            apiLogDto.setBusinessType(ApiActionEnum.REPORT_REVISIT.getNo());
            apiLogDto.setContent(e.getMessage());
            apiLogDao.addApiLog(v10ApiConfig.getV10RequestUrl() + V10InterfaceAddr.syncChannelIntentionRevisit, e.getMessage(), "同步报备复访异常");
        }
        return brDto;
    }
}